package com.lb.spring.demo.action;


import com.lb.spring.demo.service.IModifyService;
import com.lb.spring.demo.service.IQueryService;
import com.lb.spring.framework.annotation.LbAutowired;
import com.lb.spring.framework.annotation.LbController;
import com.lb.spring.framework.annotation.LbRequestMapping;
import com.lb.spring.framework.annotation.LbRequestParam;
import com.lb.spring.framework.webmvc.servlet.LbModelAndView;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 公布接口url
 * @author lb
 *
 */
@LbController
@LbRequestMapping("/web")
@Slf4j
public class MyAction {

	@LbAutowired
    IQueryService queryService;
	@LbAutowired
    IModifyService modifyService;

	@LbRequestMapping("/query.json")
	public void query(HttpServletRequest request, HttpServletResponse response,
								@LbRequestParam("name") String name){
		String result = queryService.query(name);
		out(response,result);
	}
    @LbRequestMapping("/first.html")
    public LbModelAndView query(@LbRequestParam("teacher") String teacher){
        String result = queryService.query(teacher);
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("teacher", teacher);
        model.put("data", result);
        model.put("token", "123456");
        return new LbModelAndView("first.html",model);
    }

	@LbRequestMapping("/add*.json")
	public LbModelAndView add(HttpServletRequest request, HttpServletResponse response,
                              @LbRequestParam("name") String name, @LbRequestParam("addr") String addr) throws Exception {
        String result = null;
        try {
            result = modifyService.add(name,addr);
            return out(response,result);
        } catch (Exception e) {
//			e.printStackTrace();
            Map<String,Object> model = new HashMap<String,Object>();
            model.put("detail",e.getCause().getMessage());
//			System.out.println(Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
            model.put("stackTrace", Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
            return new LbModelAndView("500",model);
        }
	}

	@LbRequestMapping("/remove.json")
	public void remove(HttpServletRequest request,HttpServletResponse response,
		   @LbRequestParam("id") Integer id){
		String result = modifyService.remove(id);
		out(response,result);
	}

	@LbRequestMapping("/edit.json")
	public void edit(HttpServletRequest request,HttpServletResponse response,
			@LbRequestParam("id") Integer id,
			@LbRequestParam("name") String name){
		String result = modifyService.edit(id,name);
		out(response,result);

	}




	private LbModelAndView out(HttpServletResponse resp, String str){
		try {
			resp.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
        return null;
    }


}
